/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.contexts;

import cn.easyplatform.EntityNotFoundException;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.util.RuntimeUtils;
import org.apache.commons.lang3.SerializationUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ReportContext implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private String id;

    private String entityId;

    private String ids;

    private char state;

    private String table;

    private RecordContext record;

    private Serializable print;

    private List<RecordContext> data;

    ReportContext(RecordContext current, String id, String entityId,
                  String ids, char state, String table) {
        this.record = current.clone();
        this.id = id;
        this.entityId = entityId;
        this.ids = ids;
        this.state = state;
        this.table = table;
    }

    public RecordContext create() {
        if (data == null)
            data = new ArrayList<RecordContext>();
        RecordContext newc = null;
        if (!Strings.isBlank(table)) {
            CommandContext cc = Contexts.getCommandContext();
            TableBean tb = cc.getEntity(table);
            if (tb == null)
                throw new EntityNotFoundException(EntityType.TABLE.getName(),
                        table);
            newc = new RecordContext(RuntimeUtils.createRecord(cc, tb, false), record.systemVariables, record.userVariables);
        } else
            newc = new RecordContext(record.getData(),
                    record.systemVariables, record.userVariables);
        data.add(newc);
        return newc;
    }

    public List<RecordContext> getData() {
        return data;
    }

    public RecordContext getRecord() {
        return record;
    }

    public String getId() {
        return id;
    }

    public String getEntityId() {
        return entityId;
    }

    public Serializable getPrint() {
        return print;
    }

    public void setPrint(Serializable print) {
        this.print = print;
    }

    public String getIds() {
        return ids;
    }

    public char getState() {
        return state;
    }

    void save(CommandContext cc) {
        if (state != 'R' && !Strings.isBlank(ids) && print != null) {
            StringBuilder sb = new StringBuilder();
            for (String name : ids.split(","))
                sb.append(record.getValue(name));
            List<FieldDo> params = new ArrayList<FieldDo>();
            if (state == 'U') {
                FieldDo fd = new FieldDo(FieldType.BLOB);
                if (print instanceof byte[])
                    fd.setValue(print);
                else
                    fd.setValue(SerializationUtils.serialize(print));
                fd.setName("content");
                params.add(fd);
                fd = new FieldDo(FieldType.DATETIME);
                fd.setValue(new Date());
                fd.setName("updatedate");
                params.add(fd);
                fd = new FieldDo(FieldType.VARCHAR);
                fd.setValue(record.getParameter("720"));
                fd.setName("updateuser");
                params.add(fd);
                fd = new FieldDo(FieldType.VARCHAR);
                fd.setValue(entityId);
                fd.setName("reportid");
                params.add(fd);
                fd = new FieldDo(FieldType.VARCHAR);
                fd.setValue(sb.toString());
                fd.setName("bizid");
                params.add(fd);
                if (cc.getBizDao()
                        .update(cc.getUser(),
                                "update sys_report_log set content=?,updatedate=?,updateuser=? where reportid=? and bizid=?",
                                params, false) > 0)
                    return;
                // 不存在，新增
                params.clear();
            }
            FieldDo fd = new FieldDo(FieldType.VARCHAR);
            fd.setValue(entityId);
            fd.setName("reportid");
            params.add(fd);
            fd = new FieldDo(FieldType.VARCHAR);
            fd.setValue(sb.toString());
            fd.setName("bizid");
            params.add(fd);
            fd = new FieldDo(FieldType.BLOB);
            if (print instanceof byte[])
                fd.setValue(print);
            else
                fd.setValue(SerializationUtils.serialize(print));
            fd.setName("content");
            params.add(fd);
            fd = new FieldDo(FieldType.DATETIME);
            fd.setValue(new Date());
            fd.setName("createdate");
            params.add(fd);
            fd = new FieldDo(FieldType.VARCHAR);
            fd.setValue(record.getParameter("720"));
            fd.setName("createdate");
            params.add(fd);
            cc.getBizDao()
                    .update(cc.getUser(),
                            "insert into sys_report_log(reportid,bizid,content,createdate,createuser) values(?,?,?,?,?)",
                            params, false);
        }
    }

}
